const EventEmitter = require('events');

class MessageHandler extends EventEmitter {
  constructor(wsServer) {
    super();
    this.wsServer = wsServer;
    this.currentSlideIndex = 1;
  }

  // 处理接收到的消息
  handleMessage(message, client) {
    const startTime = Date.now();

    try {
      // 验证消息格式
      if (!message || typeof message !== 'object') {
        this.sendError(client, '无效的消息格式', 'INVALID_FORMAT');
        return;
      }

      const { type } = message;

      switch (type) {
        case 'control':
          this.handleControlMessage(message, client, startTime);
          break;

        case 'connect':
          this.handleConnectMessage(message, client);
          break;

        case 'ping':
          this.handlePingMessage(client);
          break;

        default:
          this.sendError(client, `未知的消息类型: ${type}`, 'UNKNOWN_TYPE');
      }

    } catch (error) {
      console.error('处理消息时出错:', error);
      this.sendError(client, '处理消息失败', 'PROCESSING_ERROR');
    }
  }

  // 处理控制指令
  handleControlMessage(message, client, startTime) {
    const { action, timestamp } = message;

    if (!action || !['next', 'previous'].includes(action)) {
      this.sendError(client, '无效的控制动作', 'INVALID_ACTION');
      return;
    }

    console.log(`收到控制指令: ${action} (时间戳: ${timestamp})`);

    // 触发控制事件
    this.emit('control', action);

    // 计算处理时间
    const processingTime = Date.now() - startTime;
    if (processingTime > 50) {
      console.warn(`警告: 消息处理时间超过50ms (${processingTime}ms)`);
    }
  }

  // 处理连接消息
  handleConnectMessage(message, client) {
    const { clientId } = message;
    console.log(`客户端连接确认: ${clientId || '未知'}`);

    // 发送当前状态
    this.wsServer.sendToClient(client, {
      type: 'connected',
      serverId: 'ppt-server',
      currentSlide: this.currentSlideIndex,
      timestamp: Date.now()
    });
  }

  // 处理ping消息
  handlePingMessage(client) {
    this.wsServer.sendToClient(client, {
      type: 'pong',
      timestamp: Date.now()
    });
  }

  // 发送幻灯片更新
  sendSlideUpdate(slideIndex, imageData) {
    const startTime = Date.now();

    this.currentSlideIndex = slideIndex;

    const message = {
      type: 'slideUpdate',
      slideIndex: slideIndex,
      imageData: imageData,
      timestamp: Date.now()
    };

    this.wsServer.broadcast(message);

    const transmissionTime = Date.now() - startTime;
    console.log(`幻灯片更新已发送 (页码: ${slideIndex}, 传输时间: ${transmissionTime}ms)`);

    if (transmissionTime > 500) {
      console.warn(`警告: 传输时间超过500ms (${transmissionTime}ms)`);
    }
  }

  // 发送错误消息
  sendError(client, message, code) {
    console.error(`发送错误给客户端: ${message} (${code})`);
    
    this.wsServer.sendToClient(client, {
      type: 'error',
      message: message,
      code: code,
      timestamp: Date.now()
    });
  }

  // 广播错误消息
  broadcastError(message, code) {
    console.error(`广播错误: ${message} (${code})`);
    
    this.wsServer.broadcast({
      type: 'error',
      message: message,
      code: code,
      timestamp: Date.now()
    });
  }

  // 发送通知消息
  sendNotification(message) {
    this.wsServer.broadcast({
      type: 'notification',
      message: message,
      timestamp: Date.now()
    });
  }

  // 获取当前幻灯片索引
  getCurrentSlideIndex() {
    return this.currentSlideIndex;
  }

  // 设置当前幻灯片索引
  setCurrentSlideIndex(index) {
    this.currentSlideIndex = index;
  }
}

module.exports = MessageHandler;
